#!/usr/bin/python3

# coding=utf-8


# Created: 2019-08-10
# Updated: 2021-05-20
# Author : comet
# Description: get temperature and humidity by dht11 sensor.
# pin 3.3v(1) GPIO4(7) GND(9)

import Adafruit_DHT
import sys
import requests
import json
import socket
import psutil

# default sensor is DHT22
dht = 22
if dht == 22:
    sensor = Adafruit_DHT.DHT22
else:
    sensor = Adafruit_DHT.DHT11

loc = 'MakerSpace'
pin = 4
url = 'https://www.ictspark.com/iot/iot_receive.php'
token = 'iotofict'

def get_local_ip():
    local_ip = ""
    try:
        socket_objs = [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]
        ip_from_ip_port = [(s.connect(("114.114.114.114", 53)), s.getsockname()[0], s.close()) for s in socket_objs][0][1]
        ip_from_host_name = [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if
                             not ip.startswith("127.")][:1]
        local_ip = [l for l in (ip_from_ip_port, ip_from_host_name) if l][0]
    except (Exception) as e:
        print("get_local_ip found exception : %s" % e)
    return local_ip if ("" != local_ip and None != local_ip) else socket.gethostbyname(socket.gethostname())


def get_adp_ip_mac():
    r""" print all MAC and ip """
    myip = get_local_ip()
    dic = psutil.net_if_addrs()
    for adapter in dic:
        snicList = dic[adapter]
        mac = 'No MAC'
        ipv4 = 'No ipv4'
        ipv6 = 'No ipv6'
        for snic in snicList:
            if snic.family.name in {'AF_LINK', 'AF_PACKET'}:
                mac = snic.address
            elif snic.family.name == 'AF_INET':
                ipv4 = snic.address
            elif snic.family.name == 'AF_INET6':
                ipv6 = snic.address
            # print('%s, %s, %s, %s' % (adapter, mac, ipv4, ipv6))
        if ipv4 == myip:
            info = [adapter, mac, ipv4]
    return info


# Try to grab a sensor reading.  Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).

humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
tem = round(temperature, 1)
hum = round(humidity, 1)


netinfo = get_adp_ip_mac()
# get MAC
mymac = netinfo[1].replace(":", "")
# get local ip
myaddr = netinfo[2]
# get hostname
myname = socket.getfqdn(socket.gethostname())

if tem is not None and hum is not None:
    payload = {'ac': token, 'loc': loc, 'mac': mymac, 'name': myname, 'ip': myaddr, 'tem': tem, 'hum': hum}
    response = requests.post(url, data=payload)
    print(response.content)
    # print(response.json())
    # print('Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(temperature, humidity))
else:
    print('Failed to get reading. Try again!')
    sys.exit(1)
